﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Student
{
    class DbHelper
    {
        //连接字符串
        public readonly static string constr = "Server=.;user Id=sa;pwd=123456;database=Mxdx;";
        //创建数据库连接对象
        public static SqlConnection sqlcon = new SqlConnection(constr);

        /// <summary>
        /// 封装查询
        /// </summary>
        /// <param name="sql">select语句</param>
        /// <returns>select后的数据</returns>
        public static DataTable GetSelect(string sql)
        {
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }
            //创建适配器对象并执行sql语句
            SqlDataAdapter sqlData = new SqlDataAdapter(sql,sqlcon);
            //创建DataTable对象
            DataTable dt = new DataTable();
            //填充
            sqlData.Fill(dt);
            //关闭数据库
            sqlcon.Close();
            //返回数据
            return dt;
        }

        /// <summary>
        /// 封装增删改
        /// </summary>
        /// <param name="sql">insert delete update语句</param>
        /// <returns>insert delete update后的数据</returns>
        public static int GetIDU(string sql)
        {
            //打开数据库
            if (sqlcon.State == ConnectionState.Closed)
            {
                sqlcon.Open();
            }
            //创建SqlCommand对象连接并执行sql语句
            SqlCommand sqlcom = new SqlCommand(sql,sqlcon);
            //返回受影响的条数
            int result = sqlcom.ExecuteNonQuery();
            //返回数据
            return result;
        }
    }
}
